package com.zzld.modules.autoinn.action;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ExecutionException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.github.abel533.entity.Example;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.zzld.core.sms.SenderSms;
import com.zzld.core.utils.Base64Coder;
import com.zzld.core.utils.CookieUtils;
import com.zzld.core.utils.DateUtil;
import com.zzld.core.utils.OrderUtil;
import com.zzld.modules.autoinn.entity.Collar;
import com.zzld.modules.autoinn.entity.Coupon;
import com.zzld.modules.autoinn.entity.Customer;
import com.zzld.modules.autoinn.entity.Expense;
import com.zzld.modules.autoinn.entity.Product;
import com.zzld.modules.autoinn.entity.ProductPing;
import com.zzld.modules.autoinn.service.ICollarService;
import com.zzld.modules.autoinn.service.IConponService;
import com.zzld.modules.autoinn.service.ICustomerService;
import com.zzld.modules.autoinn.service.IExpenseService;
import com.zzld.modules.autoinn.service.IProductPingService;
import com.zzld.modules.autoinn.service.IProductService;
import com.zzld.modules.autoinn.service.IStoreService;
import com.zzld.modules.wechat.WeChat;
import com.zzld.modules.wechat.bean.WeChatBuyPost;
import com.zzld.modules.wechat.oauth.Oauth;
import com.zzld.modules.wechat.oauth.Pay;
import com.zzld.modules.wechat.util.ConfKit;
import com.zzld.modules.wechat.util.Tools;
import com.zzld.modules.wxsys.entity.WXAccount;
import com.zzld.modules.wxsys.service.IWXAccountService;

@Controller
@RequestMapping("/weixin/f/autoinn/xc/userpay")
public class WXUserPayController {

	@Autowired
	private IProductService productService;

	@Autowired
	private ICustomerService customerService;

	@Autowired
	private IExpenseService expenseService;

	@Autowired
	private IWXAccountService wxAccountService;

	@Autowired
	private IStoreService storeService;

	@Autowired
	private IProductPingService productPingService;

	@Autowired
	private IConponService couponService;

	@Autowired
	private ICollarService collarService;

	private String payurl = "/wx/autoinn/userPay";
	private String expenseurl = "/wx/autoinn/expensPay";
	private String danlist = "/wx/autoinn/orderlist";
	private static final String STATUC_SUCCESS = "SUCCESS";
	private static final String STATUC_FAIL = "FAIL";
	private final String notify_url = "http://auto.nxsh114.com/zzld/weixin/f/autoinn/xc/userpay/notice";

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public String url(Model model, HttpServletRequest request,
			@PathVariable("id") String id) {

	    String openid = CookieUtils.getCookie(request, "autoinn_session");
		String wxaccount = CookieUtils.getCookie(request, "wx_session");
		// String openid="123";
		 //String wxaccount ="12312321";
		model.addAttribute("product", productService.selectdan(id));
		try {

			openid = Base64Coder.decode(openid);
			wxaccount = Base64Coder.decode(wxaccount);

			Customer customer = null;
			try {
				customer = customerService.findCustomer(wxaccount, openid);
			} catch (Exception e1) {
				// TODO 自动生成的 catch 块
				e1.printStackTrace();
			}
			// 获取该用户未过期优惠券
		  
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("nowtime", new Date());
			map.put("wcaccount", wxaccount);
			map.put("openid", openid);
			List<Coupon> list1 = couponService.selectbyzhifu(map);
			
			model.addAttribute("coupon", list1.size()==0?null:list1);
			model.addAttribute("customer", customer);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return payurl;
	}

	public double pricea(String balance, String xprice) {
		double yue = Double.valueOf(balance == null ? "0" : balance);
		double che = Double.valueOf(xprice.replace(",",""));
		double res = (yue * 1000000) - (che * 1000000); // 余额
		return res / 1000000;

	}

	@RequestMapping(method = RequestMethod.POST)
	public String userpay(Model model, ModelMap modelmap,
			HttpServletRequest request) {
		String openid = CookieUtils.getCookie(request, "autoinn_session");
		String wxaccount = CookieUtils.getCookie(request, "wx_session");

		
	
		String o="";
		// String wxaccount = "12312321";
		 //String openid = "123";

		String balance = request.getParameter("balance") == "" ? "0" : request
				.getParameter("balance");
		String productid = request.getParameter("prid").toString();

		String orderNum = OrderUtil.generateOrderNum("XF");

		// 获取代金卷或者折扣卷
		System.out.println("开始执行");
		String zhe = request.getParameter("juanss");
		String[] strjin = null;
		if (StringUtils.isNotBlank(zhe) && !zhe.equals("0,0,0")) {
			strjin = zhe.split(",");
		}
		System.out.println("开始执行1");
		Coupon coupon = null;
		try {
			if (strjin != null) {
				coupon = couponService.selectbycolarname(strjin[2].toString());
			}
		} catch (Exception e2) {
			// TODO 自动生成的 catch 块
			e2.printStackTrace();
		}

		// 如果未获取到用户的openid和归属账号则为非法请求
		if (StringUtils.isNotBlank(openid) && StringUtils.isNotBlank(wxaccount)) {

			try {
				openid = Base64Coder.decode(openid);
				wxaccount = Base64Coder.decode(wxaccount);
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}

			String xprice = request.getParameter("xuprice").toString();

			String yprice = request.getParameter("xuprice").toString();

			if (StringUtils.isNotBlank(zhe) && !zhe.equals("0,0,0")) {
				if (strjin[1].toString().equals("0")) {
					// 使用代金卷
					xprice = String.valueOf(Double.valueOf(xprice)
							- Double.valueOf(strjin[0].toString()));
					
				
					NumberFormat ddf1=NumberFormat.getNumberInstance() ;
					ddf1.setMaximumFractionDigits(2);
					xprice = ddf1.format(Double.valueOf(xprice)) ; 
					
					
					
				} else if (strjin[1].toString().equals("1")) {
					// 使用折扣卷
					// xprice
					// =String.valueOf(Double.valueOf(xprice)*(Integer.parseInt(strjin[0].toString())*0.1));
					double x = Double.valueOf(xprice);
					double z = Double.valueOf(strjin[0].toString());
					xprice = String.valueOf(x * z * 0.1);
					NumberFormat ddf1=NumberFormat.getNumberInstance() ;
					ddf1.setMaximumFractionDigits(2);
					xprice = ddf1.format(Double.valueOf(xprice)) ; 
				}
			}

			Customer customer = null;
			try {
				customer = customerService.findCustomer(wxaccount, openid);
				if (customer == null) {
					// 账号为空,非法支付请求
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			// 判断用户是否重复订单
			/*
			 * Map<String, Object> msp = new HashMap<String, Object>();
			 * msp.put("productid", productid); msp.put("wx_account",
			 * wxaccount); msp.put("customer_id", customer.getCustomerId());
			 * Expense ding = expenseService.selectbyproid(msp); int i = ding
			 * ==null?1:ding.getIspr(); if (i==0) { modelmap.put("errormsg",
			 * "请勿重复下单"); } else {
			 */

			Map<String, Object> store = storeService.selectkey(productid);

			if (StringUtils.isNotBlank(zhe) && !zhe.equals("0,0,0")) {
				
				//判断是否重复使用优惠券
				
				
				Example ec = new Example(Collar.class);
				ec.createCriteria().andEqualTo("id", strjin[2].toString()).andEqualTo("state", 1);
			 
			  
				try {
					if(collarService.selectByExample(ec).size()>0){
						o="1";
						model.addAttribute("o", o);
						return  payurl;
					}
					
				} catch (Exception e1) {
					// TODO 自动生成的 catch 块
					e1.printStackTrace();
				}
				
				if (Double.valueOf(strjin[0].toString()) > Double
						.valueOf(request.getParameter("xuprice").toString())) {

					Expense ep = new Expense();
					ep.setCustomer_id(customer.getCustomerId());
					ep.setYfprice(Double.valueOf(xprice));
					if (StringUtils.isNotBlank(zhe) && !zhe.equals("0,0,0")) {
						if (strjin[1].toString().equals("0")) {

							ep.setDes(store.get("name").toString() + " 使用代金卷："
									+ coupon.getCouponName());
						} else if (strjin[1].toString().equals("1")) {
							ep.setDes(store.get("name").toString() + "  使用折扣卷:"
									+ coupon.getCouponName());
						}
					} else {
						ep.setDes(store.get("name").toString() + "  余额支付");
					}
					ep.setPrice(Math.abs(Double.valueOf(yprice)));
					ep.setZhekou(0);

					ep.setInnertime(new Date());
					ep.setIspr(0);
					ep.setWx_account(wxaccount);
					ep.setId(orderNum);
					ep.setProductid(productid);
					expenseService.saveexpense(ep);
					if (StringUtils.isNotBlank(zhe) && !zhe.equals("0,0,0")) {
						// 改变优惠券是否使用
						collarService.updatebystate(1, strjin[2].toString());
					}
					modelmap.put("errormsg", "支付成功");

					try {
						SenderSms.send(store.get("tel").toString(),
								"尊敬的会员:手机号为"
										+ customer.getPhoneNum().toString()
										+ "已支付洗车费用" + yprice + "元【E爱车】");
					} catch (Exception e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}
					return "redirect:/weixin/f/autoinn/xc/userpay/dinglist";
				}
			}

			// balance 不为空则为使用余额支付,为空则为微信支付
			if (StringUtils.isNotBlank(balance)) {
				// 如果使用余额支付判断是否存在差额
				double res = pricea(balance, xprice);
				// 大于等于零则走余额支付
				if (res >= 0) {
					// 执行添加订单,减少用户余额操作
					try {
						Map<String, Object> mop = new HashMap<String, Object>();

						mop.put("price", xprice);
						mop.put("id", customer.getCustomerId());
						if (customerService.updatesurplus(mop) > 0) {
							Expense ep = new Expense();
							ep.setCustomer_id(customer.getCustomerId());
							ep.setYfprice(Double.valueOf(xprice));
							if (StringUtils.isNotBlank(zhe)
									&& !zhe.equals("0,0,0")) {
								if (strjin[1].toString().equals("0")) {

									ep.setDes(store.get("name").toString()
											+ "  余额支付,使用代金卷："
											+ coupon.getCouponName());
								} else if (strjin[1].toString().equals("1")) {
									ep.setDes(store.get("name").toString()
											+ "  余额支付,使用折扣卷:"
											+ coupon.getCouponName());

								}
							} else {
								ep.setDes(store.get("name").toString()
										+ "  余额支付");
							}
							ep.setPrice(Double.valueOf(yprice));

							ep.setZhekou(0);

							ep.setInnertime(new Date());
							ep.setIspr(0);
							ep.setWx_account(wxaccount);
							ep.setId(orderNum);
							ep.setProductid(productid);
							expenseService.saveexpense(ep);
							if (StringUtils.isNotBlank(zhe)
									&& !zhe.equals("0,0,0")) {
								// 改变优惠券是否使用
								collarService.updatebystate(1,
										strjin[2].toString());
							}
							modelmap.put("errormsg", "支付成功");

							SenderSms.send(store.get("tel").toString(),
									"尊敬的会员:手机号为"
											+ customer.getPhoneNum().toString()
											+ "已支付洗车费用" + yprice + "元【E爱车】");
							return "redirect:/weixin/f/autoinn/xc/userpay/dinglist";

						}
					} catch (Exception e) {
						modelmap.put("errormsg", "出现异常");
					}

				}

			}

			double res = pricea(balance, xprice);
			
			if(res==0){
				try {
					Map<String, Object> mop = new HashMap<String, Object>();

					mop.put("price", xprice);
					mop.put("id", customer.getCustomerId());
					if (customerService.updatesurplus(mop) > 0) {
						Expense ep = new Expense();
						ep.setCustomer_id(customer.getCustomerId());
						ep.setYfprice(Double.valueOf(xprice));
						if (StringUtils.isNotBlank(zhe)
								&& !zhe.equals("0,0,0")) {
							if (strjin[1].toString().equals("0")) {

								ep.setDes(store.get("name").toString()
										+ "使用代金卷："
										+ coupon.getCouponName());
							} else if (strjin[1].toString().equals("1")) {
								ep.setDes(store.get("name").toString()
										+ " 使用折扣卷:"
										+ coupon.getCouponName());
							}
						} 
						ep.setPrice(Double.valueOf(yprice));

						ep.setZhekou(0);

						ep.setInnertime(new Date());
						ep.setIspr(0);
						ep.setWx_account(wxaccount);
						ep.setId(orderNum);
						ep.setProductid(productid);
						expenseService.saveexpense(ep);
						if (StringUtils.isNotBlank(zhe)
								&& !zhe.equals("0,0,0")) {
							// 改变优惠券是否使用
							collarService.updatebystate(1,
									strjin[2].toString());
						}
						modelmap.put("errormsg", "支付成功");

						SenderSms.send(store.get("tel").toString(),
								"尊敬的会员:手机号为"
										+ customer.getPhoneNum().toString()
										+ "已支付洗车费用" + yprice + "元【E爱车】");
						return "redirect:/weixin/f/autoinn/xc/userpay/dinglist";

					}
				} catch (Exception e) {
					modelmap.put("errormsg", "出现异常");
				}
			}
			
			if (res < 0) {
				// 判断是否微信环境, 5.0 之后的支持微信支付
				boolean isweixin = WeChat.isWeiXin(request);
				if (isweixin) {
					// 获取订单号
					// 对商品名截取, 去除空格
					String productName = store.get("name").toString();
					productName = productName.replaceAll(" ", "");
					productName = productName.length() > 17 ? productName
							.substring(0, 17) + "..." : productName;
					// package 参数封装----------------------------- //
					Map<String, String> params = new HashMap<String, String>();
					params.put("appid", ConfKit.get("AppId"));
					params.put("mch_id", ConfKit.get("partnerId"));
					params.put("nonce_str", RandomStringUtils.random(32,
							"abcdefghijklmnopqrstuvwxyz0123456789"));
					params.put("body", productName); // 商品描述。
					params.put("out_trade_no", orderNum); // 商户系统内部的订单号
					params.put(
							"total_fee",
							String.valueOf(
									Math.abs(BigDecimal.valueOf(res)
											.multiply(new BigDecimal(100))
											.doubleValue())).replace(".0", "")); // 订单总金额
					modelmap.put("qian", params.get("total_fee").toString());
					String ip = getIp(request);// 获取ip
					System.out.println("IP：" + ip);
					params.put("spbill_create_ip", ip); // ip
					params.put("notify_url", notify_url);
					params.put("trade_type", "JSAPI"); // 现金支付币种,取值： 1 （人民币）
					String coup = "";
					if (StringUtils.isNotBlank(zhe) && !zhe.equals("0,0,0")) {
						coup = "," + strjin[2].toString();

					}
					//String d =  storeService.selectkey(productid).get("name").toString();
					params.put("attach",
							productid + "," + Double.valueOf(xprice.replace(",","")) + ","
									+"f"+ "," + yprice + coup);
					modelmap.put("prepayid", params.get("attach"));
					params.put("openid", openid);

					System.out.println("开始执行预支付");
					// 获取parepay_id
					try {
						String prepayid = Pay.getPrepayid(params);
						System.out.println("预支付" + prepayid);
						params.put("prepay_id", prepayid);
						if (prepayid != null && prepayid.length() > 10) {

							// 参数
							String timeStamp = Long.toString(new Date()
									.getTime() / 1000); // 时间戳，自1970年以来的秒数
							String nonceStr = RandomStringUtils.random(32,
									"abcdefghijklmnopqrstuvwxyz0123456789"); // 32位随机数
							String packagestring = "prepay_id=" + prepayid;
							SortedMap<String, String> nativeObj = new TreeMap<String, String>();
							nativeObj.put("appId", ConfKit.get("AppId"));
							nativeObj.put("timeStamp", timeStamp);
							nativeObj.put("nonceStr", nonceStr);
							nativeObj.put("package", packagestring);
							nativeObj.put("signType", "MD5");
							String paySign = Pay.createSign(nativeObj,
									ConfKit.get("partnerKey"));// 构造签名
							nativeObj.put("paySign", paySign);

							modelmap.put("appid", ConfKit.get("AppId"));
							modelmap.put("timeStamp", timeStamp);
							modelmap.put("nonceStr", nonceStr);
							modelmap.put("package", packagestring);
							modelmap.put("paySign", paySign);
							modelmap.put("isweixin", 1);

						}

					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ExecutionException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				} else {
					modelmap.put("errormsg", "该版本不支持微信支付，请升级至微信5.0");
				}

			}
		} else {
			modelmap.put("errormsg", "非法请求");
		}

		return "/wx/autoinn/wxPay";
	}

	/**
	 * 支付通知
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "notice")
	public void notice(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		WeChatBuyPost postData = null;
		String postname = "";
		try {
			InputStream in = request.getInputStream();
			// 转换微信post过来的xml内容

			XStream xs = new XStream(new DomDriver());
			xs.alias("xml", WeChatBuyPost.class);
			String xmlMsg = Tools.inputStream2String(in);
			postData = (WeChatBuyPost) xs.fromXML(xmlMsg);
			if (postData.getReturn_code().equals("SUCCESS")
					&& postData.getResult_code().equals("SUCCESS")) {
				// 此处调用订单查询接口验证是否交易成功

				// 支付成功，商户处理后同步返回给微信参数

				// ------------------------------

				// 处理业务开始,添加充值记录,给用户余额添加金额

				// ------------------------------

				String[] strtemp = postData.getAttach().split(",");
				try {
                  
					Oauth oauthInfo = new Oauth();
					WXAccount wxaccount = wxAccountService.findwxaccount(
							postData.getAppid(), oauthInfo.getSecret());
					if (wxaccount != null) {
						// 充值记录不存在则添加


						// 操作用户余额
                       
						Customer entity = customerService
								.findCustomer(wxaccount.getAcccountId(),
										postData.getOpenid());

						
						if (entity != null) {
						
							BigDecimal surplus = entity.getSurplus();
							// 分转元

							System.out.println("开始记录3");
							BigDecimal total_fee = BigDecimal.valueOf(
									(long) postData.getTotal_fee()).divide(
									new BigDecimal(100));
							

							// 判断是否使用余额支付

							
							String xprice = strtemp[1];
							BigDecimal total_fee1 = BigDecimal.valueOf(Double
									.valueOf(xprice));
							

							
							if (total_fee.doubleValue() < total_fee1
									.doubleValue()) {
								BigDecimal res = total_fee1.subtract(total_fee);
								// System.out.println("余额扣除:"+res);

								// 执行操作余额
								
								Map<String, Object> mop = new HashMap<String, Object>();
								mop.put("price", res);
								mop.put("id", entity.getCustomerId());
								customerService.updatesurplus(mop);
								postname = "余额支付" + res + "元,";
							}

							// 更新消费记录
							
							Expense recharge = new Expense();
						
							recharge.setCustomer_id(entity.getCustomerId());
							
							recharge.setPrice(Double.valueOf(strtemp[3]
									.toString()));
							
							recharge.setId(postData.getOut_trade_no());
							
							recharge.setZhekou(0);
							
							recharge.setYfprice(total_fee.doubleValue());
							
							recharge.setWx_account(wxaccount.getAcccountId());
						
							String jid = "";
							Coupon c = null;
							System.out.println("开始记录14和"+strtemp.length);
							if (strtemp.length==5) {
								
								c = couponService.selectbycolarname(strtemp[4].toString());
                                jid=c.getCouponName();
							}
							
							String d =  storeService.selectkey(strtemp[0].toString()).get("name").toString();
							
							recharge.setDes(d + "," + postname
									+ "微信支付" + total_fee.doubleValue() + "元!使用"
									+jid);
							
							recharge.setInnertime(DateUtil.strToDate(postData
									.getTime_end()));
							
							recharge.setProductid(strtemp[0]);
							System.out.println("1,"+strtemp[0]+"和2,"+strtemp[1]
									+"和3,"+strtemp[2]+"和4,"+strtemp[3]);
							expenseService.saveexpense(recharge);
							
							
							if (strtemp.length==5) {
								//改变优惠券使用状态

								collarService.updatebystate(1, strtemp[4].toString());
							}
							System.out.println("开始记录数据");
							Map<String,Object> map = storeService.selectkey(strtemp[0].toString());
					
							// 支付成功
							try {
								SenderSms.send(map.get("tel").toString(),
										"尊敬的会员:手机号为" + entity.getPhoneNum() + "已支付洗车费用:"
												+ strtemp[3] + "元【E爱车】");
							} catch (Exception e) {
								// TODO 自动生成的 catch 块

								e.printStackTrace();
							}
							
						}
					}

				} catch (Exception e) {
					// TODO Auto-generated catch block

					e.printStackTrace();
				}

				// ------------------------------

				// 处理业务完毕

				// ------------------------------

				
			
				String noticeStr = setXML(STATUC_SUCCESS, "");
				response.getWriter().write(noticeStr);
			} else {
				// 支付失败

				String noticeStr = setXML(STATUC_FAIL, "支付失败");
				response.getWriter().write(noticeStr);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 支付失败

		String noticeStr = setXML(STATUC_FAIL, "支付失败");
		response.getWriter().write(noticeStr);
	}

	public static String setXML(String return_code, String return_msg) {
		return "<xml><return_code><![CDATA[" + return_code
				+ "]]></return_code><return_msg><![CDATA[" + return_msg
				+ "]]></return_msg></xml>";
	}

	@RequestMapping(value = "expense", method = RequestMethod.GET)
	public String expenseurl() {
		return expenseurl;
	}

	@RequestMapping(value = "dinglist", method = RequestMethod.GET)
	public String danlist(Model model, HttpServletRequest request) {
		String isyi = request.getParameter("isyi") == null ? "3" : request
				.getParameter("isyi");

		String openid = CookieUtils.getCookie(request, "autoinn_session");
		String wxaccount = CookieUtils.getCookie(request, "wx_session");
		try {
			wxaccount = Base64Coder.decode(wxaccount);
			openid = Base64Coder.decode(openid);
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}

		//String wxaccount = "12312321";
		//String openid = "123";
		Customer customer = null;
		try {
			customer = customerService.findCustomer(wxaccount, openid);
			if (customer == null) {
				// 账号为空,非法支付请求
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("wxaccount", wxaccount);
		map.put("customerid", customer.getCustomerId());
		map.put("ispr", isyi.equals("3") ? null : isyi);

		List<Expense> e = expenseService.selectbydinglist(map);
		for (int i = 0; i < e.size(); i++) {

			ProductPing p = productPingService.selectbypingcount(e.get(i)
					.getId());
			if (isyi.equals("3")) {
				if (p == null) {
					e.get(i).setIsping(0);
				} else {
					e.get(i).setId(null);
				}
			} else {
				if (p == null) {
					e.get(i).setIsping(0);
				} else {
					e.get(i).setIsping(1);
				}
			}

		}

		if (e.size()==0) {
			model.addAttribute("ding", null);
		} else {
			model.addAttribute("ding", e);
		}
		return danlist;
	}

	/**
	 * 获取ip
	 * 
	 * @param request
	 * @return
	 */
	public static String getIp(HttpServletRequest request) {
		if (request == null)
			return "";
		String ip = request.getHeader("X-Requested-For");
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Forwarded-For");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		String[] rip = ip.split(",");
		if (StringUtils.isNotBlank(ip) && StringUtils.isNotBlank(rip[0])) {
			ip = rip[0];
		} else {
			ip = "127.0.0.1";
		}

		return ip;
	}

	// 金额验证	
	public static boolean isNumber(String str) {
		java.util.regex.Pattern pattern = java.util.regex.Pattern
				.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$"); // 判断小数点后2位的数字的正则表达式
		java.util.regex.Matcher match = pattern.matcher(str);
		if (match.matches() == false) {
			return false;
		} else {
			return true;
		}
	}
}
